package gui.popup;

import java.util.List;

import gui.App;
import gui.dialogs.Confirm;
import models.Client;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;

public class ClientPopup extends Popup<Client>{

	private Text givenname, lastname, adress, phone, email;
	
	public ClientPopup(App app) {
		super(app);
	}
	
	@Override
	public void buildForm(Composite formPanel, Client client) {
		setTitle_modelType("Klant");
		
		formPanel.setLayout(new GridLayout(2, false));
		
		createFormItem_label(formPanel, "Voornaam");
		givenname = createFormItem_text(formPanel, client.getGivenname());

		createFormItem_label(formPanel, "Achternaam");
		lastname = createFormItem_text(formPanel, client.getLastname());

		createFormItem_label(formPanel, "Adres");
		adress = createFormItem_text(formPanel, client.getAdress());

		createFormItem_label(formPanel, "Telefoon");
		phone = createFormItem_text(formPanel, client.getPhone());

		createFormItem_label(formPanel, "Email");
		email = createFormItem_text(formPanel, client.getEmail());
	}

	@Override
	public Client createEmptyModel() {
		return new Client();
	}

	@Override
	public boolean isDataValid() {
		ParseError errorBox = new ParseError();
		String gn = givenname.getText();
		errorBox.obligatedField(gn);
		errorBox.fieldLength(gn, 50);
		
		String ln = lastname.getText();
		errorBox.obligatedField(ln);
		errorBox.fieldLength(ln, 50);
		
		String ad = adress.getText();
		errorBox.obligatedField(ad);
		errorBox.fieldLength(ad, 50);
		
		String ph = phone.getText();
		errorBox.fieldLength(ph, 20);
		
		String em = email.getText();
		errorBox.fieldLength(em, 50);
		
		if (errorBox.errorsPresent()) {
			alertInvalidData(errorBox.getErrorString());
			return false;
		}
		
		// Check for similar client
		Client dummyClient = createEmptyModel();
		updateModel(dummyClient);
		List<Client> similarClients = getApp().getClientList().getSimilarClients(dummyClient);
		similarClients.remove(getEntry());
		if ( ! similarClients.isEmpty()) {
			boolean cont = new Confirm(getShell(), 
				"Gelijkaardige klant gevonden", 
				"Er is een betaande klant gevonden (" + similarClients.get(0).getName() + ") die overeenkomt " +
						"met deze klant. Wilt u toch deze gelijkaardige klant toevoegen?"
			).open().accepted;
			if (!cont) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void updateModel(Client client) {
		client.setGivenname(givenname.getText());
		client.setLastname(lastname.getText());
		client.setAdress(adress.getText());
		client.setPhone(phone.getText());
		client.setEmail(email.getText());
	}
}
